import 'package:eleapp/res/strings.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../dio/http_request.dart';
import '../../dio/api.dart';

import '../../widget/emptydata.dart';

class Camera extends StatefulWidget {
  const Camera({super.key});

  @override
  State<Camera> createState() => _CameraState();
}

class _CameraState extends State<Camera> {
  List classList = [];
  bool isReady = false;
  _load() async {
    List listRes = await Request2.post<List>(Api.classlist, {});
    setState(() {
      isReady = true;
      classList = listRes;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    // initState不允许async 只能这样请求异步数据
    Future.delayed(
      Duration.zero,
      () => setState(() {
        _load();
      }),
    );
  }

  loadClass(List data) {
    List<Widget> treeList = [];
    for (int i = 0; i < data.length; i++) {
      treeList.add(Column(
        children: [
          ListTile(
            leading: const Icon(Icons.class_),
            title: Text('${data[i]['name']}'),
            trailing: const Icon(Icons.arrow_right_sharp),
            onTap: () {
              // Navigator.pushNamed(context, '/tasklist', arguments: {'id': 1});
              Get.toNamed('/tasklist', arguments: {
                'class_id': data[i]['id'],
                'class_name': data[i]['name']
              });
            },
          ),
          const Divider()
        ],
      ));
    }

    return treeList;
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: double.infinity,
      child: Column(
        children: [
          SizedBox(
            height: 50,
            child: Center(
              child: Text(StringStyles.myclasses.tr),
            ),
          ),
          Expanded(
            flex: 1,
            child: isReady // 等待请求完成再展示列表或者空数据 避免空数据切换列表的不良感观
                ? classList.isNotEmpty
                    ? ListView(
                        children: loadClass(classList),
                      )
                    : const EmptyData()
                : const SizedBox(),
          )
        ],
      ),
    );
  }
}
